//
//  FlickrParser.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-4-6.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "FlickrParser.h"

#import "DataManager.h"
#import "PhotosetInfo.h"


@implementation FlickrParser

-(id)init{
	if(self = [super init]){
		tags = [[Stack alloc] init];
	}
	return self;
}

-(BOOL)parseString:(NSString *)xmlContent{
	const char *xmlData = [xmlContent UTF8String];
	NSData *data = [[NSData alloc] initWithBytes:xmlData length:strlen(xmlData)];
	BOOL ret = [self parseData:data];
	[data release];
	return ret;
}

-(BOOL)parseData:(NSData *)data{
	if(fparser){
		[fparser autorelease];
	}
	success = NO;
	fparser = [[NSXMLParser alloc] initWithData:data];
	[fparser setDelegate:self];
	[fparser setShouldProcessNamespaces:NO];
	return [fparser parse];
}

#pragma mark NSXMLParserDelegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
	attributes:(NSDictionary *)attributeDict{
	
	// TODO startElement
	currentElement = [elementName copy];
	
	if([elementName isEqualToString:@"rsp"]){
		NSString *state = [attributeDict objectForKey:@"stat"];
		success = [state isEqualToString:@"ok"];
	}else if([elementName isEqualToString:@"auth"]){
		result = [[NSMutableDictionary alloc] init];
		tagType = TAG_TYPE_AUTH;
	}else if([elementName isEqualToString:@"frob"]){
		tagType = TAG_TYPE_FROB;
	}else  if([elementName isEqualToString:@"user"]){
		if(tagType == TAG_TYPE_AUTH){
			NSString *uid = [attributeDict objectForKey:@"nsid"];
			DataManager *dm = [DataManager sharedDataManager];
			dm.userId = uid;
			NSMutableDictionary *dict = result;
			[dict setObject:uid forKey:@"nsid"];
			
			NSString *uname = [attributeDict objectForKey:@"username"];
			dm.userName = uname;
			[dict setObject:uname forKey:@"username"];
			
			NSString *fname = [attributeDict objectForKey:@"fullname"];
			dm.userFullName = fname;
			[dict setObject:fname forKey:@"fullname"];
		}
	}else if([elementName isEqualToString:@"photosets"]){
		// photoset
		result = [[NSMutableArray alloc] init];
		tagType = TAG_TYPE_PHOTOSET;
	}else if([elementName isEqualToString:@"photoset"]){
		// TODO Check the autorelase
		PhotosetInfo *set = [[[PhotosetInfo alloc] init] autorelease];
		set.setID = [attributeDict objectForKey:@"id"];
		if(tagType == TAG_TYPE_PHOTOSET){
			set.primary = [attributeDict objectForKey:@"primary"];
			set.secret = [attributeDict objectForKey:@"secret"];
			set.serverID = [attributeDict objectForKey:@"server"];
			set.farmID = [attributeDict objectForKey:@"farm"];
			NSString *ps = [attributeDict objectForKey:@"photos"];
			set.photos = [ps integerValue];
			if([result isKindOfClass:[NSMutableArray class]]){
				NSMutableArray *arr = (NSMutableArray *)result;
				[arr addObject:set];
			}
		}
		
	}
	
	// 添加标签
	[tags push:elementName];
	
	
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
	// TODO text
	NSString *cTag = nil;
	if(![tags isEmpty]){
		cTag = [tags peek];
		if([cTag isEqualToString:@"frob"]){
			result = [string copy];
		}else if([cTag isEqualToString:@"token"]){
			if(tagType == TAG_TYPE_AUTH){
				DataManager *dm = [DataManager sharedDataManager];
				dm.token = string;
				NSMutableDictionary *dict = result;
				[dict setObject:string forKey:@"token"];
			}
		}else if([cTag isEqualToString:@"perms"]){
			if(tagType == TAG_TYPE_AUTH){
				DataManager *dm = [DataManager sharedDataManager];
				dm.perms = string;
				NSMutableDictionary *dict = result;
				[dict setObject:string forKey:@"perms"];
			}
		}else if([cTag isEqualToString:@"photoid"]){
			result = [string copy];
		}else if([cTag isEqualToString:@"title"]){
			
			if(tagType == TAG_TYPE_PHOTOSET){
				// TODO 针对当前 photoset 设置标题属性
				if([result isKindOfClass:[NSMutableArray class]]){
					NSMutableArray *arr = (NSMutableArray *)result;
					NSInteger size = [arr count];
					if(size > 0){
						PhotosetInfo *ps = (PhotosetInfo *)[arr objectAtIndex:(size - 1)];
						ps.title = string;
					}
				}
			}
		}else if([cTag isEqualToString:@"description"]){
			if(tagType == TAG_TYPE_PHOTOSET){
				// TODO 针对当前 photoset 设置标题属性
				if([result isKindOfClass:[NSMutableArray class]]){
					NSMutableArray *arr = (NSMutableArray *)result;
					NSInteger size = [arr count];
					if(size > 0){
						PhotosetInfo *ps = (PhotosetInfo *)[arr objectAtIndex:(size - 1)];
						ps.description = string;
					}
				}
			}
		}

	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
	if([elementName isEqualToString:@"photosets"]){
		tagType = -1;
	}
	// 弹出标签
	[tags pop];
}

- (void)parserDidEndDocument:(NSXMLParser *)parser{
	[tags removeAll];
	tagType = -1;
}


-(id)getResult{
	return result;
}

-(BOOL)isSuccess{
	return success;
}

-(void)dealloc{
	if(fparser != nil){
		[fparser release];
	}
	if(tags != nil){
		[tags release];
	}
	if(result != nil){
		[result release];
	}	
	[super dealloc];
}

@end
